package com.tongcao.cn.netty.aio;

import com.tongcao.cn.netty.Io;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.Random;
import java.util.concurrent.ExecutionException;

/**
 * @author:tongcao
 * @since:2019/7/9 10:40
 * Description:
 */
public class AioClient implements Runnable, Io {


    private AsynchronousSocketChannel asynchronousSocketChannel;

    public AioClient(AsynchronousSocketChannel asynchronousSocketChannel) {
        this.asynchronousSocketChannel = asynchronousSocketChannel;
    }

    public AioClient() throws Exception {
        asynchronousSocketChannel = AsynchronousSocketChannel.open(); // 打开通道
    }

    /**
     * // 创建连接 和NIO一样
     */
    public void connnet() {
        asynchronousSocketChannel.connect(new InetSocketAddress(IP_ADDRESS, PORT));
    }


    public void write(String request) {

        try {
            asynchronousSocketChannel.write(ByteBuffer.wrap(request.getBytes())).get();
            final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            asynchronousSocketChannel.read(byteBuffer).get();
            byteBuffer.flip();
            final byte[] restBytes = new byte[byteBuffer.remaining()];
            byteBuffer.get(restBytes);
            System.out.println("new String(restBytes,\"utf-8\".trim()) = " + new String(restBytes, "utf-8".trim()));

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10; i++) {
            final AioClient client = new AioClient();
            client.connnet();
            new Thread(client, "myClient").start();
            final Random random = new Random(System.currentTimeMillis());
            String expression = random.nextInt(10)+OPERATORS[random.nextInt(4)]+(random.nextInt(10)+1);
            client.write(expression);

        }

    }

    @Override
    public void run() {
        while (true) {

        }
    }
}